package com.butterfly.mvc.servlet;

import com.butterfly.mvc.annotation.Controller;
import com.butterfly.mvc.annotation.RequestMapping;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by DouDou on 2016/9/28.
 */
public class ClassScan {

    public ClassScan() {
    }

    public static void scan(String filePath, Map<String, ActionBean> serviceMap) throws ClassNotFoundException {
        //System.out.println(file.getPath());
        //Class clazz = Class.forName(file.getPath());
        String path = filePath;
        if(filePath.endsWith(".class")) {
            path = filePath.substring(0, filePath.lastIndexOf(".class"));
        }
        Class clazz = Class.forName(path);

        /**如果不存在controller，则结束解析**/
        if(!clazz.isAnnotationPresent(Controller.class)){
            return;
        }

        Method[] methods = clazz.getDeclaredMethods();
        for(Method m:methods){
            if(m.isAnnotationPresent(RequestMapping.class)){
                ActionBean actionBean = scanMethod(clazz, m);
                serviceMap.put(actionBean.getPath(),actionBean);
            }
        }

    }

    private static ActionBean scanMethod(Class clazz, Method m){
        ActionBean ab = new ActionBean();
        String reqPath = "/";
        ab.setClassPath(clazz.getName());
        ab.setMethod(m.getName());

        Annotation annotation = clazz.getAnnotation(Controller.class);
        if(annotation instanceof  Controller){
            Controller con = (Controller) annotation;
            reqPath += con.value();
        }

        ab.setReqType(m.getAnnotation(RequestMapping.class).method());
        ab.setPath(reqPath +"/"+ m.getAnnotation(RequestMapping.class).value());

        ab.setParams(m.getParameterTypes());
        return ab;
    }

    public static void main(String[] args){
        String filePath = "D:\\liuchunlin\\work\\idea\\annotationmvc\\src\\main\\java\\com\\butterfly\\mvc\\action\\LoginAction";
        File file = new File(filePath);
        Map<String,ActionBean> map = new HashMap<String, ActionBean>();
        try {
            ClassScan.scan("com.butterfly.mvc.action.IndexAction",map);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println(map);
    }
}
